<template>
  <div id="header">
    <h1>搜索用户</h1>
    <form @submit.prevent>
      <input
        type="text"
        v-model="text"
        placeholder="enter the name you search"
      />
      <button @click="seekUser">搜索</button>
    </form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "Header",
  data() {
    return {
      text: "",
    };
  },
  methods: {
    async seekUser() {
      //点击先判断输入的内容是不是空
      let newText = this.text.trim();
      if (!newText) {
        alert("请输入搜索内容");
        return;
      }
      //不为空就执行发送请求操作
      //先改变loading 的状态
      this.$bus.$emit("setLoading", true);

      //发送请求
      let res = await axios({
        method: "GET",
        url: "https://api.github.com/search/users",
        params: {
          // querystring参数
          q: this.text,
        },
      });
      // console.log(res.data.items);
      let arr = res.data.items;
      let newArr = arr.map((user) => {
        return {
          id: user.id,
          login: user.login,
          html_url: user.html_url,
          avatar_url: user.avatar_url,
        };
      });
      // console.log(newArr);
      // 调用给展示组件添加数据的方法
      this.$bus.$emit("addUser", newArr);
      this.$bus.$emit("setLoading", false);
    },
  },
};
</script>

<style>
#header {
  width: 100%;
  height: 200px;
}
#header h1 {
  margin-bottom: 30px;
}
</style>